package com.ns.dcjh.utils.upyun

import android.content.Context
import android.widget.Toast
import com.google.gson.Gson
import com.tencent.mm.opensdk.utils.Log
import com.upyun.library.common.ParallelUploader
import com.upyun.library.common.Params
import com.upyun.library.common.UploadEngine
import com.upyun.library.listener.UpCompleteListener
import com.upyun.library.listener.UpProgressListener
import com.upyun.library.utils.UpYunUtils
import java.io.File
import java.io.IOException
import java.net.URLEncoder
import java.util.concurrent.ExecutorService

class UpYunUtil {

    var SPACE = "dichanw"
    var OPERATER = "frontend"
    var PASSWORD = "ShY0I8hDcIsn4lDxzACBxIAkqlwece8T"
    var HEAD = "https://vod.dichanw.com"

    private var parallelUploader: ParallelUploader? = null

    /**
     * 上传单个文件
     */
    fun formUpload(
        context: Context,
        file: File,
        cityKey: String,
        uid: String,
        upYunCompleteListener: UpYunCompleteListener
    ) {
        var savePath = getSavePath(file, cityKey, uid)
        var paramsMap: Map<String, Any> = HashMap()
        paramsMap = mapOf(
            Params.BUCKET to SPACE,
            Params.SAVE_KEY to savePath,
            Params.CONTENT_LENGTH to file.length(),
            //可选参数回调地址，
            Params.RETURN_URL to "httpbin.org/post"
        )
        Toast.makeText(context, "filePath = " + savePath, Toast.LENGTH_LONG)
            .show()
        //进度回调，可为空
        val progressListener =
            UpProgressListener { bytesWrite, contentLength ->
                val percent = ((100 * bytesWrite) / contentLength).toInt()
                upYunCompleteListener.onProgress(percent)
            }
        //结束回调，不可为空
        val completeListener =
            UpCompleteListener { isSuccess, response, error ->
                try {
                    if (isSuccess) {
                        var result: String? = null
                        if (response != null) {
                            result = response.body!!.string()
                        } else if (error != null) {
                            result = error.toString()
                        }

                        val entity: UpYunEntity = Gson().fromJson(result, UpYunEntity::class.java)
                        val url = entity.url
                        upYunCompleteListener.complete(HEAD + url, entity)
                    } else {
                        upYunCompleteListener.fail(error.message)
                    }
                } catch (e: IOException) {
                    e.printStackTrace()
                    upYunCompleteListener.fail(e.message)
                }
            }
        //表单上传（本地签名方式）
        UploadEngine.getInstance().formUpload(
            file,
            paramsMap,
            OPERATER,
            UpYunUtils.md5(PASSWORD),
            completeListener,
            progressListener
        )

    }

    /**
     * 上传单个文件
     */
    fun formUpload(file: File, path: String, upYunCompleteListener: UpYunCompleteListener) {
        var paramsMap: Map<String, Any> = HashMap()
        paramsMap = mapOf(
            Params.BUCKET to SPACE,
            Params.SAVE_KEY to path,
            Params.CONTENT_LENGTH to file.length(),
            //可选参数回调地址，
            Params.RETURN_URL to "httpbin.org/post"
        )
        //进度回调，可为空
        val progressListener =
            UpProgressListener { bytesWrite, contentLength ->
                val percent = ((100 * bytesWrite) / contentLength).toInt()
                upYunCompleteListener.onProgress(percent)
            }
        //结束回调，不可为空
        val completeListener =
            UpCompleteListener { isSuccess, response, error ->
                try {
                    if (isSuccess) {
                        var result: String? = null
                        if (response != null) {
                            result = response.body!!.string()
                        } else if (error != null) {
                            result = error.toString()
                        }

                        val entity: UpYunEntity = Gson().fromJson(result, UpYunEntity::class.java)
                        val url = entity.url
                        upYunCompleteListener.complete(HEAD + url, entity)
                    } else {
                        upYunCompleteListener.fail(error.message)
                    }
                } catch (e: IOException) {
                    e.printStackTrace()
                    upYunCompleteListener.fail(e.message)
                }
                Log.e("UpYunUtil 120", "UpYunUtil 120")
            }
        //表单上传（本地签名方式）
        UploadEngine.getInstance().formUpload(
            file,
            paramsMap,
            OPERATER,
            UpYunUtils.md5(PASSWORD),
            completeListener,
            progressListener
        )

    }

    fun getInstance(): UploadEngine? {
        return UploadEngine.getInstance();
    }


    fun formUploadCancel() {
        val engine = UploadEngine.getInstance()
        val engineClass: Class<*> = UploadEngine::class.java
        val privateEngine = engineClass.getDeclaredField("executor")
        privateEngine.isAccessible = true
        val es = privateEngine.get(engine) as? ExecutorService
        es?.shutdownNow()
    }


    fun parallelUpload(
        context: Context,
        file: File,
        cityKey: String,
        uid: String,
        upYunCompleteListener: UpYunCompleteListener
    ) {
        parallelUploader = ParallelUploader(SPACE, OPERATER, UpYunUtils.md5(PASSWORD))
        parallelUploader?.setCheckMD5(true)
        parallelUploader?.setOnProgressListener { bytesWrite, contentLength ->
            val percent = ((100 * bytesWrite) / contentLength).toInt()
            upYunCompleteListener.onProgress(percent)
        }
        val filePath = getSavePath(file, cityKey, uid)
        Toast.makeText(context, "filePath = " + filePath, Toast.LENGTH_LONG).show()
        var paramsMap: Map<String, String> = HashMap()
        paramsMap = mapOf(
            Params.BUCKET to SPACE,
            Params.SAVE_KEY to getSavePath(file, cityKey, uid),
            //可选参数回调地址，
            Params.RETURN_URL to "httpbin.org/post"
        )

        parallelUploader?.upload(
            file,
            filePath,
            paramsMap
        ) { isSuccess, response, error ->
            try {
                if (isSuccess) {
                    var result: String? = null
                    if (response != null) {
                        result = HEAD + filePath
                    } else if (error != null) {
                        result = error.toString()
                    }

//                    val entity: UpYunEntity = Gson().fromJson(result, UpYunEntity::class.java)
//                    val url = entity.url
                    upYunCompleteListener.complete(result, null)
                } else {
                    upYunCompleteListener.fail(error.message)
                }
            } catch (e: IOException) {
                e.printStackTrace()
                upYunCompleteListener.fail(e.message)
            }
        }

    }


    fun uploadPause() {
        if (parallelUploader != null) {
            parallelUploader?.pause()
            parallelUploader = null
        }
    }


    /**
     * 保存在服务器的文件路径（可优化）
     */
    private fun getSavePath(file: File, cityKey: String, uid: String): String {
        return "/upload/${TimeUtils.getCurrDayFormat("yyyyMM")}/" + cityKey + "_" + uid + "_" + System.currentTimeMillis() +
                ".${getFileSuffix(file)}"
    }

    /**
     * 获取文件后缀
     */
    private fun getFileSuffix(file: File): String {
        return file.name.substring(file.name.lastIndexOf(".") + 1)
    }

}